from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
from random import randint
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pymongo


class SnygShop:
    mongo_client = pymongo.MongoClient('localhost', 27017)
    collection = mongo_client['snyg']['sp_info']

    driver_path = Service(executable_path='./chromedriver.exe')
    options = Options()
    options.add_experimental_option("detach", True)
    options.add_argument('--start-maximized')
    options.add_argument('blink-settings=imagesEnabled=false')
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    browser = webdriver.Chrome(service=driver_path, options=options)

    @classmethod
    def get_detailPage(cls):
        cls.browser.get('https://www.suning.com/')
        wait = WebDriverWait(cls.browser, 10)
        ipt = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="searchKeywords"]')))
        ipt.send_keys('手机')
        btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="searchSubmit"]')))
        time.sleep(2)
        btn.click()
        time.sleep(randint(1, 3))

    @classmethod
    def drop_down(cls):
        for  i in range(1,12):
            js = f"document.documentElement.scrollTop={i}*1500"
            cls.browser.execute_script(js)
            time.sleep(1)

    @classmethod
    def parse_data(cls):
        cls.drop_down()

        li_lis = cls.browser.find_elements(By.XPATH, '//*[@id="product-list"]/ul/li')
        for i in li_lis:
            title = i.find_element(By.XPATH, './div/div/div[2]/div[2]/a').text
            price = i.find_element(By.XPATH, './div/div/div[2]/div[1]/span').text

            print(title,price)
            item = {
                'title': title,
                'price': price
            }
            print(item)
            cls.save_data(item)
        time.sleep(6)
        cls.next_page()

    @classmethod
    def save_data(cls, item):
        cls.collection.insert_one(item)

    @classmethod
    def next_page(cls):
        try:
            wait = WebDriverWait(cls.browser, 10)
            next_btn = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'next')))
            if next_btn:
                cls.browser.execute_script("arguments[0].click();", next_btn)
                # 被其他元素覆盖了 采用js来点击
                cls.parse_data()
            else:
                cls.browser.close()
        except Exception as e:
            print(e)
            cls.browser.quit()


if __name__ == '__main__':
    SnygShop.get_detailPage()
    SnygShop.parse_data()
